# -*- coding: utf-8 -*-
"""
Manim脚本生成器
"""

from typing import Any, Dict, List
from pathlib import Path


class ManimGenerator:
    """Manim脚本生成器"""

    def __init__(self, scenes: List[Dict[str, Any]], resolution: str, fps: int):
        """
        初始化生成器

        Args:
            scenes: 场景列表
            resolution: 分辨率
            fps: 帧率
        """
        self.scenes = scenes
        self.resolution = resolution
        self.fps = fps

    def generate_script(self) -> str:
        """
        生成Manim脚本

        Returns:
            Manim Python代码
        """
        scene_texts = [
            (s.get("narration") or s.get("title") or "").strip()
            for s in self.scenes
            if (s.get("narration") or s.get("title") or "").strip()
        ]

        code_lines = [
            "from manim import *",
            "",
            "class Generated(Scene):",
            "    def construct(self):",
            "        scene_texts = [",
            *[f"            {repr(t)}," for t in scene_texts if t],
            "        ]",
            "        for txt in scene_texts:",
            "            m = Text(txt, font_size=42)",
            "            self.play(Write(m))",
            "            self.wait(1)",
            "            self.play(FadeOut(m))",
            "",
        ]

        return "\n".join(code_lines)

    def save_script(self, output_dir: Path) -> Path:
        """
        保存脚本到文件

        Args:
            output_dir: 输出目录

        Returns:
            脚本文件路径
        """
        output_dir.mkdir(parents=True, exist_ok=True)
        script_path = output_dir / "manim_script.py"

        code = self.generate_script()
        script_path.write_text(code, encoding="utf-8")

        return script_path
